package com.qiyue.common.exception.handler;

import com.qiyue.common.constant.CommonConstants;
import com.qiyue.common.exception.BaseException;

import com.qiyue.vo.BaseResult;
import com.qiyue.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;


/**
 * Created by y747718944 on 2018/1/25
 * 捕获异常统一处理
 *  在controller中被抛出的异常，没有被catch处理的情况下，该类会统一处理
 *  此种方法不仅可以作用于Controller，同样的在DAO层、service层也可
 */
@ControllerAdvice("com.qiyue")
@ResponseBody
public class GlobalExceptionHandler extends BaseResult {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BaseException.class)
    public Result baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        logger.error(ex.getMessage(),ex);
        response.setStatus(500);
        return new Result(ex.getMessage(),ex.getErrorCode());
    }

    @ExceptionHandler(Exception.class)
    public Result otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(500);
        logger.error(ex.getMessage(),ex);
        return new Result(ex.getMessage(),CommonConstants.ExceptionConstants.EX_OTHER_CODE);
    }
}
